package com.atguigu.gulimallcart.config;

import com.atguigu.common.Const.CartConst;
import com.atguigu.common.Const.OauthConst;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimallcart.vo.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class gulimallInterceptor implements HandlerInterceptor {
    //用于同一线程之间来共享数据
    public static ThreadLocal<UserInfo> userInfoThreadLocal = new ThreadLocal<>();

    //请求到达服务之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录的用户(session必须是从SpringSession获取到的(存在redis中))
        Object attribute = request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
        MemberEntityVo memberEntityVo = (MemberEntityVo) request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
        //已登录用户
        UserInfo userInfo = new UserInfo();
        if (memberEntityVo != null) {
            //已登录用户将userId赋值
            userInfo.setUserId(memberEntityVo.getId());
        }
        //扫描Cookie，查看是否有临时用户的标志
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //已经有了临时用户的标志，将userInfo的key设置上值
                if (cookie.getName().equals(CartConst.CART_TEM_USER_KEY)) {
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                }
            }
        }
        //设置临时用户的标志,用于离线购物车来确定用户的身份
        if (userInfo.getUserKey() == null) {
            userInfo.setUserKey(UUID.randomUUID().toString());

        }
        //设置值。
        userInfoThreadLocal.set(userInfo);

        //放行
        return true;
    }

    //请求到达服务之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //这里要在cookie中放好用户的信息
        UserInfo userInfo = userInfoThreadLocal.get();
        /**
         * 如果是临时用户，那么的就给他设置上cookie的一些列信息，如果不是，那么就没有必要.
         * 此处可以不加这个判断，那么每次都会给cookie自动
         *
         */
        if (!userInfo.isTempUser()) {
            Cookie cookie = new Cookie(CartConst.CART_TEM_USER_KEY, userInfo.getUserKey());
            //设置作用域
            cookie.setDomain(CartConst.DO_MAIN);
            //设置存活时间
            cookie.setMaxAge(CartConst.MAX_AGE);
            response.addCookie(cookie);
        }
    }
}
